package com.xuedakun.sample.xasdk.volley_test;

import com.android.volley.VolleyError;
import com.xuedakun.xasdk.XLog;
import com.xuedakun.xasdk.net.HttpUtils;
import com.xuedakun.xasdk.net.JsonUtils;
import com.xuedakun.xasdk.net.volley.VolleyCallback;

/**
 * Created by xuedakun on 2017/6/4 13:40
 * 自定义VolleyCallback
 * @version : v1.0
 * @project : xasdk
 * @Email : dakun611@Gmail.com
 */

public class SampleVolleyCallback<R extends SampleBaseResult> extends VolleyCallback<R>{

    private static final String LOG_TAG = "SampleVolleyCallback";

    private static final int REQUEST_OK = 0;

    private static final int REQUEST_ERROR = -1;

    private static final int REQUEST_NO_NET = -2;

    public SampleVolleyCallback(Class<R> clazz) {
        super(clazz);
    }

    @Override
    public void onResponse(String response) {
        if(requestCallback != null) {
            try{
                result = JsonUtils.fromJsonString(response, clazz);
                result.setRequestCode(HttpUtils.HTTP_CODE_OK);
                result.setJson(response);
                if(result.getCode() == REQUEST_OK) {
                    requestCallback.onRequestSucceed(result);
                }else{
                    requestCallback.onRequestFail(result);
                }
            }catch (Exception e) {
                XLog.e(LOG_TAG, "网络请求本地异常");
                result = newResultInstance();
                result.setRequestCode(REQUEST_ERROR);
                result.setJson(response);
                requestCallback.onRequestFail(result);
                e.printStackTrace();
            }
        }
    }

    @Override
    public void onErrorResponse(VolleyError error) {
        super.onErrorResponse(error);
        XLog.e(LOG_TAG, "网络请求HTTP异常" + error.networkResponse.statusCode);
//        result.setMsg(XApplication.getContext().getString(R.string., error.networkResponse.statusCode));
        if(requestCallback != null) {
            requestCallback.onRequestFail(result);
        }
    }
}
